using System.Data;
using MySql.Data.MySqlClient;
using Microsoft.Extensions.Configuration;

namespace hao_Common.Dapper.Db
{
    /// <summary>
    /// MySQL数据库连接工厂实现
    /// </summary>
    public class DapperDbConnectionFactory : IDbConnectionFactory
    {
        private readonly string _connectionString;

        public DapperDbConnectionFactory(IConfiguration configuration)
        {
            _connectionString = configuration.GetConnectionString("DefaultConnection");
        }

        public IDbConnection CreateConnection()
        {
            // 打开连接后强制设置会话字符集，避免中文/emoji被替换为问号
            var conn = new MySqlConnection(_connectionString);
            conn.Open();
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandText = "SET NAMES utf8mb4";
                cmd.ExecuteNonQuery();
            }
            return conn;
        }

        // 新增：测试数据库连接
        public bool TestConnection()
        {
            try
            {
                using var conn = new MySqlConnection(_connectionString);
                conn.Open();
                return conn.State == ConnectionState.Open;
            }
            catch
            {
                return false;
            }
        }
    }
}